package leetcode;

import common.ListNode;

/**
 * 删除链表的倒数第N个节点  
 */
public class LeetCode19 {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (n <= 0 || head == null) return head;
        ListNode tempNode = new ListNode(0);
        tempNode.next = head;
        // p1为要删除节点的前继节点
        ListNode p1 = tempNode, p2 = head;
        // p2先走n步
        for (int i = 0; i < n; i++) p2 = p2.next;
        // p1、p2一起走
        while (p2 != null) {
            p2 = p2.next;
            p1 = p1.next;
        }
        p1.next = p1.next.next;
        return tempNode.next;
    }
}